package com.bobochang.warehouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bobochang.warehouse.entity.Department;
import com.bobochang.warehouse.entity.Result;
import com.bobochang.warehouse.entity.User;
import com.bobochang.warehouse.mapper.DepartmentMapper;
import com.bobochang.warehouse.page.Page;
import com.bobochang.warehouse.service.DepartmentService;
import com.bobochang.warehouse.utils.DigestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author LiY
 */

@Slf4j
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public Result saveDeparment(Department department) {
        Department department1 = departmentMapper.findDepartmentByName(department.getDepartmentName());
        if (department1 != null) {//用户已存在
            return Result.err(Result.CODE_ERR_BUSINESS, "该部门已存在！");
        }

        departmentMapper.insertDempartment(department);
        return Result.ok("添加部门成功！");
    }

    @Override
    public Result updateDepartment(Department department) {
        departmentMapper.updateDepartmentById(department);
        return Result.ok("修改成功");
    }

    @Override
    public void deleteDepartmentById(Integer departmentId) {

        QueryWrapper<Department> queryWrapper = new QueryWrapper<Department>();
        queryWrapper.eq("id", departmentId);
        departmentMapper.delete(queryWrapper);
    }

    @Override
    public Result searchById(Integer departmentId) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<Department>().eq("id", departmentId);
        return Result.ok(departmentMapper.selectOne(queryWrapper));
    }

    @Override
    public List<Department> selectAll() {
        return departmentMapper.selectList(null);
    }

    @Override
    public Page queryDepartmentPage(Page page, Department department) {
        //查询用户总行数
        int userCount = departmentMapper.selectCount(null);
        //分页查询用户
        List<Department> userList = departmentMapper.selectDepartmentPage(page, department);

        //将查询到的总行数和当前页数据组装到Page对象
        page.setTotalNum(userCount);
        page.setResultList(userList);

        return page;
    }

    public String findById(Integer departmentId) {
        if(departmentId == null|| departmentId == 0){
            return "无";
        }
        return departmentMapper.selectOne(
                new LambdaQueryWrapper<Department>()
                        .eq( Department::getId, departmentId)
        ).getDepartmentName();
    }
}
